package org.dreamwork.tools.simulator.connector.managed;

import org.dreamwork.db.SQLite;
import org.dreamwork.injection.AInjectionContext;
import org.dreamwork.persistence.DatabaseSchema;
import org.dreamwork.tools.simulator.connector.data.schema.DummyInterfaceSchema;
import org.dreamwork.tools.simulator.connector.data.schema.RequestLogSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;

@Resource
@AInjectionContext
public class LocalConfig {
    private final Logger logger = LoggerFactory.getLogger (LocalConfig.class);

    @Resource
    public SQLite getSqlite () throws IOException {
        String home = System.getProperty ("user.home");
        Path dir = Paths.get (home, ".dummy-connector");
        if (!Files.exists (dir)) {
            Files.createDirectories (dir);
        }
        String path = dir.toRealPath ().toString ();
        logger.info ("temp path = {}", path);
        SQLite sqlite = SQLite.get (path + "/dummy-connector.sqlite");
        logger.info ("sqlite = {}", sqlite);

        DatabaseSchema.register (DummyInterfaceSchema.class);
        DatabaseSchema.register (RequestLogSchema.class);
        if (!sqlite.isTablePresent ("dummy_interface")) {
            try {
                sqlite.createSchemas ();
            } catch (SQLException ex) {
                throw new RuntimeException (ex);
            }
        }
        if (!sqlite.isTablePresent ("request_log")) {
            DatabaseSchema schema = DatabaseSchema.MAP.get (RequestLogSchema.class);
            sqlite.execute (schema.getCreateDDL ());
        }
        return sqlite;
    }
}